<template>
  <div v-loading="loading" :class="{'mobile-detail-wrap':showMobilePage}" class="detail-order-info">
    <orderInfo :class="{'mobile-el-form':showMobilePage}" :detail-data="detailData" />
    <DetailTabs v-model="activeId" :tabs="tabs" style="margin-bottom: 16px;" />
    <IncomeItem
      v-if="hasRouteAuth('mengli:iPOrder:incomeRead') || hasRouteAuth('mengli:iPOrder:incomeAdmin') || isAdmin"
      v-show="activeId === 0"
      ref="incomeItemRef"
      v-model="incomeListData.items"
      :income-list-data="incomeListData"
      :has-add-auth="hasRouteAuth('mengli:iPOrder:incomeAdd') || isAdmin"
      :has-edit-auth="hasRouteAuth('mengli:iPOrder:incomeEdit') || isAdmin"
      :has-delete-auth="hasRouteAuth('mengli:iPOrder:incomeDelete') || isAdmin"
      :detail-data="detailData"
      :is-detail="true"
      show-count-fields
      style="margin-top:10px;"
      @freshData="freshData"
      @editIcomeItem="editIcomeItem"
      @addIcomeItem="addIcomeItem"
      @deleteIcomeItem="deleteIcomeItem" />
    <ipOrderIncome
      v-if="activeId === 1"
      ref="ipOrderIncomeRef"
      :detail-data="detailData"
      :order-id="orderId"
      style="margin-top:10px;"
      @getDetail="getData" />
    <costBreakdownComponent
      v-show="activeId === 2"
      ref="costBreakdownRef"
      :cost-breakdown="costBreakdown"
      :order-id="Number(orderId)"
      :show-settlement-btn="true"
      :order-num="detailData.orderNum"
      :is-detail="true"
      :is-mengli="true"
      :cost-belong-type="2"
      show-link-income
      style="margin-top:10px;"
      @toLinkIncome="toLinkIncome"
      @update="update"
    />
    <!-- <cost-info :detail-data="detailData" /> -->
    <!-- 核销记录 -->
    <charge-off-record
      v-if="detailData && detailData.financeRecord"
      v-show="activeId === 3"
      :records="detailData.financeRecord"
      :order-id="Number(orderId)"
      :is-not-add-account="hasRouteAuth('mengli:iPOrder:addAccount') || isAdmin"
      :client-name="detailData.clientName"
      :client-id="detailData.clientId"
      :order-type="detailData.orderType"
      style="padding:0;margin-bottom: 26px;"
      @getDetail="getData" />
    <div v-if="detailData" v-show="activeId === 4" class="select-related-container" >
      <InvoiceAndContract
        ref="ContractSelect"
        :show-empty="true"
        :is-edit="true"
        :title="'合同信息'"
        :sub-title="'关联合同'"
        :type="1"
        :init-request-data="hasRouteAuth('crm:contract:read')"
        style="margin-top: 10px;"
        placeholder="请输入合同编号/合同名称"
        @changeSelect="changeSelect" />
    </div>
    <InvoiceTable v-if="activeId === 4" :table-data="detailData.invoiceInfo || []"/>
    <!-- <div v-if="detailData" v-show="activeId === 4" class="select-related-container">
      <div style="height:30px;display:flex;align-items:center;">
        <div><Title title="发票信息" /></div>
        <IconAmountLayout :amount="detailData.invoiceAmount/100" amount-text="有效发票金额" />
      </div>
      <InvoiceAndContract
        ref="InvoiceSelect"
        :is-edit="true"
        :show-empty="true"
        :is-disabled="false"
        :related-contract-style="{
          position: 'absolute',top: '3px',right: '0px'
        }"
        :init-request-data="hasRouteAuth('crm:receipt:read')"
        :type="2"
        placeholder="请输入发票编号/发票号码"
        @changeSelect="changeSelect" />
    </div> -->
    <!-- <div style="margin-top:20px;">
      <Title :title="'操作记录'" style="padding: 32px 0"/>
      <log-time-line v-if="operateLogs && operateLogs.length > 0" :logs="operateLogs" :edit-api="setLogRemarks" @success="editRemarkSuccess" />
      <div v-else class="empty-container">
        <img :src="emptyImg" alt="">
        <div class="empty-text">暂无操作日志</div>
      </div>
    </div> -->
    <fixed-pagination>
      <div class="center">
        <el-button v-if="hasRouteAuth('mengli:iPOrder:edit')" type="primary" size="small" class="submit-btn" @click="toEdit">编辑订单</el-button>
        <el-button type="info" class="back-btn cancel-btn-style" size="small" @click="toBack"><span style="font-size:16px;">返回</span></el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
// 组件
import Title from '@/components/Title';
import orderInfo from '@/components/Mengli/mengliOrder/ipOrderInfo';
import ipOrderIncome from '@/components/Mengli/mengliOrder/ipOrderIncome';
import IncomeItem from '@/components/Mengli/mengliOrder/incomeItem/index';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import ChargeOffRecord from '@/components/CreateOrder/orderDetail/chargeOffRecord';
import costBreakdownComponent from '@/components/Cost/costList';
import LogTimeLine from '@/components/Common/logTimeLine';
import IconAmountLayout from '@/components/Common/IconAmountLayout';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
// import CostInfo from '@/components/Mengli/mengliOrder/costInfo';
// api
import { getipLicense, contractAndinvoiceInfo,
  getLog, setLogRemarks, editMengliIpOrder,
  addIpIncomeList, editIpIncomeList, deleteIpIncomeList, getIpIncomeList
} from '@/api/mengliOrder';
import ElMessage from '@/utils/message';
import emptyImg from '@/assets/empty-data-icon.png';
import { hasRouteAuth } from '@/utils/permission';
import { moneyFilter } from '@/filters/number';
import { mapState } from 'vuex';
import InvoiceTable from '@/components/Finance/invoiceTable';

export default {
  components: { Title, orderInfo, IconAmountLayout, ipOrderIncome, IncomeItem,
    InvoiceAndContract, ChargeOffRecord, LogTimeLine, costBreakdownComponent, DetailTabs, InvoiceTable },
  filters: { moneyFilter },
  data() {
    return {
      emptyImg,
      orderId: '',
      loading: false,
      detailData: {},
      operateLogs: [],
      costBreakdown: {
        page: 1,
        perPage: 20,
        costList: [],
        total: 0
      },
      activeId: 0,
      tabs: [
        { id: 0, name: '收入列表' },
        { id: 1, name: '分成信息' },
        { id: 2, name: '成本列表' },
        { id: 3, name: '核销记录' },
        { id: 4, name: '发票合同' }
      ],
      incomeListData: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    invoiceValidAmount() {
      // 有效发票金额：统计列表发票状态=已完成的发票金额
      let price = null;
      const invoiceInfo = this.detailData.invoiceInfo;
      if (!invoiceInfo || invoiceInfo.length === 0) return '--';
      invoiceInfo.forEach(i => {
        // 状态： 0: '草稿中', 1: '审批中', 2: '未过审', 3: '已作废', 4: '已完成', 5: '待提交'
        if (i.status === 4) {
          price = (price || 0) + i.amountFen;
        }
      });
      return price === null ? '--' : (price / 100);
    }
  },
  created() {
    this.orderId = this.$route.params.id || '';
    this.getData();
    this.getIncomeList();
  },
  methods: {
    hasRouteAuth,
    setLogRemarks(params) {
      const orderType = this.detailData.orderType || 0;
      return new Promise((resolve, reject) => {
        params.orderType = orderType;
        setLogRemarks(params).then(res => {
          resolve(res);
        }).catch((err) => {
          reject(err);
        });
      });
    },
    getData(muted = false, params = {}) {
      if (!muted) this.loading = true;
      // this.getOperateReports();
      getipLicense({ id: this.orderId, ...params }).then(res => {
        this.loading = false;
        if (res.data) {
          if (res.data.ipAry) {
            const ip = [];
            res.data.ipAry.forEach(i => {
              ip.push(`${i.ipFigure || '--'}/${i.ipSeries || '--'}`);
            });
            res.data.ipInfo = ip.join(',');
          }
          this.$nextTick(() => {
            if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(res.data.contract);
            if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(res.data.invoiceInfo);
            if (this.$refs.costBreakdownRef) this.$refs.costBreakdownRef.insertDetail(res.data.costBreakdown); // 传值给成本
          });
          this.detailData = res.data;
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    update(type, val) {
      if (type === 'perPage') {
        this.costBreakdown.perPage = val;
      } else if (type === 'page') {
        this.costBreakdown.page = val;
      }
      this.getData();
      this.getIncomeList();
    },
    // 合同和发票修改
    changeSelect(selectData) {
      // this.toSubmit({ muted: true });
      const params = {
        id: this.orderId,
        orderType: this.detailData.orderType || 0
      };
      // 发票和合同
      const relatedIds = this.getRelatedIds();
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      contractAndinvoiceInfo(params).then(res => {
        if (res.code === 200) {
          // ElMessage.success('关联成功');
          this.getData();
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    },
    getOperateReports() {
      const data = {
        id: this.orderId,
        type: 0,
        orderType: this.detailData.orderType || 0
      };
      getLog(data).then(res => {
        if (res.code === 200) {
          this.operateLogs = res.data;
        }
      });
    },
    editRemarkSuccess() {
      this.getOperateReports();
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 0;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    },
    toEdit() {
      this.$router.push({
        name: 'mengliOrderEdit',
        params: { id: this.orderId },
        query: { type: this.detailData.orderType || 0 }
      });
    },
    editFun() {
      const paramsObj = JSON.parse(JSON.stringify(this.detailData));
      if (paramsObj.id) {
        if (paramsObj.invoiceInfo && paramsObj.invoiceInfo.length > 0) {
          paramsObj.invoiceIds = paramsObj.invoiceInfo.map(i => i.id).join(',');
        }
        if (paramsObj.contract && paramsObj.contract.length > 0) {
          paramsObj.contractIds = paramsObj.contract.map(i => i.id).join(',');
        }
        editMengliIpOrder(paramsObj).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功');
            this.getData();
          } else {
            this.$message.error(res.message);
          }
        }).catch(() => {
          this.btnLoading = false;
        });
      }
    },
    /**
     * 收入项
     */
    toLinkIncome(item) {
      if (this.$refs.incomeItemRef) {
        this.activeId = 0;
        this.$refs.incomeItemRef.setParams({ incomeItemNo: item.linkIncomeItemNo });
      }
    },
    editIcomeItem(params, listParams) {
      editIpIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.getIncomeList(listParams);
          this.getData();
          if (this.$refs.ipOrderIncomeRef) this.$refs.ipOrderIncomeRef.getData(true);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    addIcomeItem(params, listParams) {
      params.mengliId = this.orderId;
      addIpIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.getIncomeList(listParams);
          this.getData();
          if (this.$refs.ipOrderIncomeRef) this.$refs.ipOrderIncomeRef.getData(true);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteIcomeItem(params, listParams) {
      deleteIpIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.getIncomeList(listParams);
          this.getData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    freshData(data) {
      this.getIncomeList(data);
    },
    getIncomeList(params = {}) {
      if (!params.page) params.page = 1;
      if (!params.perPage) params.perPage = 20;
      getIpIncomeList({ id: this.orderId, ...params }).then(res => {
        if (res.code === 200) {
          this.incomeListData = res.data;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.detail-order-info {
  min-height: calc(100vh - 80px);
  padding: 20px;
  background: #fff;
  padding-bottom: 55px;
  &.mobile-detail-wrap {
    padding: 12px 12px 55px 12px;
  }
  &::v-deep {
    .el-form-item .el-form-item__label {
      color: #999;
    }
    .el-form-item .el-form-item__content {
      color: #333;
    }
  }
}
.select-related-container {
  margin-bottom:30px;
  position: relative;
  padding: 0;
  &::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
  }
}
.empty-container {
  text-align: center;
  position: relative;
  margin-top: 20px;
  img {
    width: 90px;
  }
  .empty-text {
    color: #999;
    max-width: 300px;
    font-size: 14px;
    margin: 0 auto;
  }
}
.detail-order-info {
  &::v-deep {
    .el-row .el-card {
      border: none;
      background: #fff;
      border-radius: 0;
      -webkit-box-shadow: none;
      box-shadow: none;
    }
    .create-cost-card {
      padding: 0;
      padding-top: 15px;
    }
  }
}
</style>x
